﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Controls;
using HeritageAcademy.Models.DataModels;
using HeritageAcademy.Models.Loaders;
using HeritageAcademy.Shared;
using HeritageAcademy.Window.Resources;

namespace HeritageAcademy.Models.ViewModels
{
    public class TestWizardPageViewModel : INotifyPropertyChanged
    {
        #region Parameters

        private string _source;
        private TestResultsLoader _resultsLoader;
        private ReadOnlyCollection<AnswerViewModel> _availableAnswers;
        bool _isCurrentPage;
        int _currentPageNumber = 1;
        string _currentPageId;
        
        #endregion

        #region Ctor
        
        public TestWizardPageViewModel(TestResultsLoader resultsLoader)
        {
            _resultsLoader = resultsLoader;
        }
        
        #endregion

        #region Properties

        /// <summary>
        /// Test page source path.
        /// </summary>
        public string Source
        {
            get { return _source; }
            set 
            { 
                _source = value;
                OnPropertyChanged("Source");
            }
        }

        /// <summary>
        /// Current page number in the list of all pages.
        /// </summary>
        public int Number
        {
            get { return _currentPageNumber; }
            set 
            { 
                _currentPageNumber = value;
                OnPropertyChanged("Number");
            }
        }

        /// <summary>
        /// Current page id.
        /// </summary>
        public string Id
        {
            get { return _currentPageId = (DataFileParsing.SeparateString(
                                                    ((AnswerViewModel)_availableAnswers[0]).Tag.ToString(),
                                                    Strings.Page_Id_Separator
                                                    ))[0]; }
        }
        
        #region AvailableAnswers

        /// <summary>
        /// Returns a read-only collection of all AnswerType that the user can select.
        /// </summary>
        public ReadOnlyCollection<AnswerViewModel> AvailableAnswers
        {
            get { return _availableAnswers; }
        }

        public void GetAvailableAnswers(Control ctrl)
        {
            List<AnswerViewModel> list = new List<AnswerViewModel>();
            StackPanel sp = VisualTree.FindChild<StackPanel>(ctrl, "spAnswers");

            if (sp != null)
            {
                foreach (var item in sp.Children)
                {
                    if (item.GetType() == typeof(CheckBox))
                    {
                        list.Add(new AnswerViewModel{ Tag = ((CheckBox)item).Tag.ToString(), IsSelected = false});
                        ((CheckBox)item).Click += TestWizardPageViewModel_CheckBox_Click;
                    }
                    if (item.GetType() == typeof(RadioButton))
                    {
                        list.Add(new AnswerViewModel{ Tag = ((RadioButton)item).Tag.ToString(), IsSelected = false});
                        ((RadioButton)item).Click += TestWizardPageViewModel_RadioButton_Click;
                        ((RadioButton)item).Unchecked += TestWizardPageViewModel_RadioButton_Click;
                    }
                }
            }

            //list.Sort();
            _availableAnswers = new ReadOnlyCollection<AnswerViewModel>(list);

            // Create results initial record
            CreateResultsRecord();
        }

        void CreateResultsRecord()
        {
            bool exists = false;
            PageResult pageResult = new PageResult { Id = this.Id };
            pageResult.Time = "";

            // find the previously created record
            // and drop the status to "false" (not checked)
            foreach (var result in _resultsLoader.Model.Results)
            {
                if (result.Id == pageResult.Id)
                {
                    exists = true;
                    foreach (var answer in result.Answers)
                        answer.Status = "false";
                }
            }

            // if not found create the new one
            if (!exists)
            {
                string[] str;
                for (int i = 1; i <= _availableAnswers.Count; i++)
                {
                    str = DataFileParsing.SeparateString(((AnswerViewModel)_availableAnswers[i - 1]).Tag.ToString(), Strings.Page_Id_Separator);
                    Answer ans = new Answer { Id = str[1], Status = "false" };
                    pageResult.Answers.Add(ans);
                }
                _resultsLoader.Model.Results.Add(pageResult);
                _resultsLoader.Save();
            }
        }

        void UpdateResultsRecord(string pageid, string answerid, bool? isChecked)
        {
            foreach (var result in _resultsLoader.Model.Results)
                if (result.Id == pageid)
                    foreach (var answer in result.Answers)
                        if (answer.Id == answerid)
                            answer.Status = (isChecked == true) ? "true" : "false";
            _resultsLoader.Save();
        }

        public void FixTime(string pageid, string time)
        {
            foreach (var result in _resultsLoader.Model.Results)
                if (result.Id == pageid)
                    result.Time = time;
            _resultsLoader.Save();
        }

        void TestWizardPageViewModel_CheckBox_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateResultsRecord(Separate(sender)[0], Separate(sender)[1], ((CheckBox)sender).IsChecked);
        }

        void TestWizardPageViewModel_RadioButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateResultsRecord(Separate(sender)[0], Separate(sender)[1], ((RadioButton)sender).IsChecked);
        }

        string[] Separate(object sender)
        {
            return DataFileParsing.SeparateString(((Control)sender).Tag.ToString(), Strings.Page_Id_Separator);
        }

        #endregion

        public bool IsCurrentPage
        {
            get { return _isCurrentPage; }
            set
            {
                if (value == _isCurrentPage)
                    return;

                _isCurrentPage = value;
                this.OnPropertyChanged("IsCurrentPage");
            }
        }

        #endregion

        #region Public Methods
        
        /// <summary>
        /// Returns true if the user has filled in this page properly
        /// and the wizard should allow the user to progress to the 
        /// next page in the workflow.
        /// </summary>
        public bool IsValid()
        {
            return _currentPageId != null;
        }

        #endregion
        
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
